var idChanged = true;
var vcChanged = true;
var idFlag = false;
var vcFlag = false;

$(function(){
	if( document.getElementById( "register" ) ){
		$('#idInfo').html( "输入你常用邮箱或手机号" );
		$('#proxyId').attr( "alt", "常用邮箱或手机号" );
		$('#pwdInfo').html( "6-16个字符，字母、数字、下划线，首个字符必须为字母！");
	}
	
	
	$('#proxyId').blur(function(){
		check_proxyId();
	});
	
	$('#proxyId').change( function(){
		idChanged = true;
		idFlag = false;
	});
	
	$('#password').blur(function(){
		check_pwd();
	});
	
	$('#rePassword').blur(function(){
		check_repwd();
	});
	
	$('#vc').blur( function(){
		check_vc();
	});
	
	$('#vc').change( function(){
		vcChanged = true;
		vcFlag = false;
	});
	
	$('#register').submit( function(event){
		return idFlag&&check_pwd()&&check_repwd()&&vcFlag;
	});
	
	$('#login').submit(function(event){
		var result = idFlag && check_pwd();
		if( result ){
			saveAccount( $('#save_pwd') );
		}
		return result;
	});
})


function check_proxyId(){
	var idstr = $('#proxyId').val();
	
	if( idstr=="" ){
		$('#idInfo').html("哇擦，你见过空的账号？");
		return false;
	}
	
	var phoneReg=/^((13[0-9])|(15[0-9])|(18[0-9]))[0-9]{8}$/;
	var emailReg=/\b(^['_A-Za-z0-9-]+(\.['_A-Za-z0-9-]+)*@([A-Za-z0-9-])+(\.[A-Za-z0-9-]+)*((\.[A-Za-z0-9]{2,})|(\.[A-Za-z0-9]{2,}\.[A-Za-z0-9]{2,}))$)\b/;
	
	var digitReg=/^\d+$/;
	
	if( phoneReg.test( idstr ) || emailReg.test( idstr ) ){
		idFlag = true;
		if( document.getElementById("register") && idChanged ){
			idFlag = false;
			var url = 'http://localhost:8080/sm3/user/userAction!checkExist?user.proxyId=' + idstr;
			ajax( url, callback );
			idChanged=false;
		}
		return idFlag;
	}else{
		if( digitReg.test( idstr ) ){
			$('#idInfo').html("手机号是长成这样的？");
		}else{
			$('#idInfo').html( "邮箱不是这个样子的吧！" );
		}
		return false;
	}
	
	//处理返回信息
	function callback( request ){
		var text = request.responseText;
		if( text.search(/&/) == -1 ){
			idFlag = false;
		}else{
			text = text.substr(0, text.search( /&/) );
			idFlag = true;
		}
		$('#idInfo').html( text );
	}
}

function check_vc(){
	$('#vcInfo').html();
	var vc= $('#vc').val();
	
	var vcReg=/^\w{5}$/;
	if( !vcReg.test( vc ) ){
		//alert( vc );
		$('#vcInfo').html( "验证码错误" );
		return false;
	}
	var url = 'http://localhost:8080/sm3/user/verifyCodeAction!checkVc?vc=' + vc;
	if( vcChanged ){
		ajax( url, callback );
		vcChanged = false;
	}
	
	return vcFlag;
	
	function callback( request ){
		var text = request.responseText;
		if( text.search(/&/) == -1 ){
			vcFlag = false;
		}else{
			text = text.substr(0, text.search( /&/) );
			vcFlag = true;
		}
		$('#vcInfo').html( text );
	}
}

function check_name(){
	$('#nameInfo').html();
	var name=$('#name').val();
	var teg=/^[\u4e00-\u9faf]{2,3}$/;
	if(name==""){
		$('#nameInfo').html("姓名不能为空");
		return false;
	}
	if(!teg.test(name)){
		$('#nameInfo').html("姓名格式不对");
		return false;
	}
	$('#nameInfo').html( "你的输入正确" );
	return true;
}

function check_pwd(){
	$('#pwdInfo').html();
	var pwd=$('#password').val();
	if(pwd==""){
		$('#pwdInfo').html("密码不能为空");
		return false;
	}
	var userId = $('#proxyId').val();
	var score = testpass( pwd, userId );
	
	if( score==-4 ){
		$('#pwdInfo').html( "你的那个…有点短…" );
	}else if( score==-5){
		$( '#pwdInfo').html( "太长啦……");
	}else if( score==-2 ){
		$('#pwdInfo').html( "呐呢？上面的跟下面的长得一样！");
	}else if( score==-1 ){
		$( '#pwdInfo' ).html( "密码含字母、数字、特殊字符中的两组！");
	}else if( score==-3){
		$('#pwdInfo').html( "首个字符必须为大小写字母！" );
	}else{
		var text = score<34? '弱':( score<68 ? '一般' : '强' );
		$('#pwdInfo').html( "密码强度: " + text );
		return true;
	}
	return false;
}
function check_repwd(){
	var repwd=$('#rePassword').val();
	if(repwd==""){
		$('#rePwdInfo').html("确认密码不能为空");
		return false;
	}
	else if(repwd!=$('#password').val()){
		$('#rePwdInfo').html("密码输入与第一次不一样");
		return false;
	}else{
		if( check_pwd() ){
			$('#rePwdInfo').html("Well Done!");
			return true;
		}else{
			$( '#rePwdInfo' ).html( "密码错误!");
			return false;
		}
	}
}

function testpass(password,username){
    var score = 0;
    if (password.length < 6 ) { return -4; }
    if( password.length >16 ){ return -5 }
    if (typeof(username) != 'undefined' && password.toLowerCase() == username.toLowerCase()){return -2}
    
    if( password.match(/^[a-zA-Z]+$/) || password.match(/^\d+$/) ){		//若都为字母，或数字，密码不符
    	return -1;
    }
    
    if( !(password.charAt(0)+"").match(/^[a-zA-Z]+$/) ){					//若首字符不为字符，密码错误
    	return -3;
    }
    
    score += password.length*4;
    score += ( repeat(1,password).length - password.length ) * 1;
    score += ( repeat(2,password).length - password.length ) * 1;
    score += ( repeat(3,password).length - password.length ) * 1;
    score += ( repeat(4,password).length - password.length ) * 1;
    score += ( repeat(5,password).length - password.length ) * 1;
    score += ( repeat(6,password).length - password.length ) * 1;
    if (password.match(/(.*[0-9].*[0-9].*[0-9])/)){ score += 5;}
    if (password.match(/(.*[!,@,#,$,%,^,&,*,?,_,~].*[!,@,#,$,%,^,&,*,?,_,~])/)){ score += 5 ;}
    if (password.match(/([a-z].*[A-Z])|([A-Z].*[a-z])/)){ score += 10;}
    if (password.match(/([a-zA-Z])/) && password.match(/([0-9])/)){ score += 15;}
    if (password.match(/([!,@,#,$,%,^,&,*,?,_,~])/) && password.match(/([0-9])/)){ score += 15;}
    if (password.match(/([!,@,#,$,%,^,&,*,?,_,~])/) && password.match(/([a-zA-Z])/)){score += 15;}
    
    if ( score < 0 ){score = 0;}
    if ( score > 100 ){ score = 100;}
    return score;
    
    function repeat(len,str){
	    var res = "";
	    for (var i = 0; i < str.length; i++ ){
	        var repeated = true;
	        for (var j = 0, max = str.length - i - len; j < len && j < max; j++){
	            repeated = repeated && (str.charAt(j + i) == str.charAt(j + i + len));
	        }
	        if (j < len) repeated = false;
	        if (repeated) {
	            i += len - 1;
	            repeated = false;
	        }else{
	            res += str.charAt(i);
	        }
	    }
	    return res;
    }
}


/**
 * 为注册页面 register.jsp 中验证码 input的onFocus属性
 * 当获得焦点时
 * 将该区域下的元素设为可见
 * Create Date : 2013-09-20
 * @param ipt string(id of input)/ Input
 * @return null
 * @author Liushimao
 */
function showImage( ipt ){
	//验证是ipt是否为 input 的id或Input对象
	if( typeof ipt === 'string' ){
		var ipt = document.getElementById( ipt );
	}
	var iptName = ipt.nodeName.toLowerCase();
	if( !iptName.match( /^input/ ) ){
		alert( 'not a valide Input object');
		return;
	}
	//创建一个img
	function setImgAttr( img, idStr, clazz, srcStr, altStr ){
		img.setAttribute( 'id', idStr );
		img.setAttribute( 'class', clazz );
		img.setAttribute( 'src', srcStr );		
		img.setAttribute( 'alt', altStr );		
	};
	//创建img
	var vcImg=document.getElementById( 'vcImg' );
	if( vcImg ){
		return;
	}
	vcImg=document.createElement( 'img' );
	var srcStr = 'http://localhost:8080/sm3/user/verifyCodeAction';
	setImgAttr( vcImg, 'vcImg', 'imgclz', srcStr, '验证码' );
	
	//创建链接
	var vcA = document.getElementById( 'vcA' );
	if( vcA ){
		return;
	}
	vcA=document.createElement( 'a' );
	vcA.setAttribute( "href", "javascript:refreshAc( 'vcImg' );" );
	vcA.setAttribute( 'id', 'vcA' );
	//acA.setAttribute( "href", "#" );
	
	//为链接创建一个 img
	var imgOfnewA=document.createElement( 'img' );	
	setImgAttr( imgOfnewA, 'vcAimg', 'vcAImg', 'images/rff.png', '刷新' );
	vcA.appendChild( imgOfnewA );
	
	//将acImg放入指定区域
	var tac=document.getElementById( 'tvc' );
	tvc.appendChild( vcImg );
	tvc.appendChild( vcA );
}


/**
 * 注册页面 register.jsp 中所用
 * 此函数 为验证码图片后的链接所写，在函数showImg(...)中用到
 * 此函数用于向服务器发送图片请求
 * Create Date : 2013-09-20
 * @param acImgID 验证码图片的 id
 * @return null
 * @author Liushimao
 */
function refreshAc( vcImgID ){
	if( !Date.now ){
		Date.now=function(){
			return (new Date()).getTime();
		}
	}
	var srcStr="http://localhost:8080/sm3/user/verifyCodeAction?time=" + Date.now();
	document.getElementById( vcImgID ).setAttribute( "src", srcStr );
	vcChanged=true;
	vcFlag=false;
}


function saveAccount(){
	if( idFlag && check_pwd() ){
		var idstr = $('#proxyId').val();
		var pwd = $.md5( $('#password').val() );
		$.removeCookie( 'ACCOUNT' );
		$.cookie( 'ACCOUNT', idstr+":"+pwd, { expires:14 } );
	}
}

function addCookie( ipt ){
	var isChecked = ipt.checked;
	if( isChecked ) {
		saveAccount();
	}else{
		var account = $.cookie( 'ACCOUNT' );
		if( account.length>37 ){
			$.cookie( 'ACCOUNT_DUP', account );
			$.removeCookie( 'ACCOUNT', '' );
		}
	}
}